<template>
<!--  https://www.mocky.io/v2/5cc8019d300000980a055e76-->
  <a-flex>
    <a-upload
      v-model:file-list="fileList"
      name="avatar"
      list-type="picture-card"
      class="avatar-uploader"
      :show-upload-list="true"
      :before-upload="beforeUpload"
      @change="handleChange"
      :max-count="maxLength"
      @preview="handlePreview"
      :multiple="props.multiple"
    >
      <div v-if="fileList.length < maxLength">
        <loading-outlined v-if="loading"></loading-outlined>
        <plus-outlined v-else></plus-outlined>
        <div class="ant-upload-text">{{ placeholder }}</div>
      </div>
    </a-upload>
    <div class="upload-tips" v-if="props.showTips">
      <div class="tips_rows">文件大小: 不超过<span class="striking">{{props.maxSize}}MB</span></div>
      <div class="tips_rows">文件格式: <span class="striking">{{props.type}}</span></div>
    </div>
  </a-flex>
  <a-modal :open="previewVisible" :title="previewTitle || '预览图片'" :footer="null" @cancel="handleCancel">
    <img alt="example" style="width: 100%" :src="previewImage" />
  </a-modal>
</template>
<script lang="ts" setup>
import { ref, watch } from 'vue';
import { PlusOutlined, LoadingOutlined } from '@ant-design/icons-vue';
import { message } from 'ant-design-vue';
import type { UploadChangeParam, UploadProps } from 'ant-design-vue';

const props = defineProps({
  showTips: {
    type: Boolean,
    required: false,
    default: false,
  },
  placeholder: {
    type: String,
    required: true,
  },
  type: {
    type: String,
    required: true,
  },
  maxLength: {
    type: Number,
    required: true,
  },
  maxSize: {
    type: Number,
    required: true,
  },
  multiple: {
    // 选择多张图片
    type: Boolean,
    default: false,
  },
  value: {
    type: [Array, String], // 根据实际情况调整类型
    default: () => [],
  },
})
const loading = ref<boolean>(false)
const emit = defineEmits(['update:value'])
const placeholder = props.placeholder
const maxLength = props.maxLength
const maxSize = props.maxSize
const fileList = ref(props.value||[]);
const previewImage = ref('')
const previewTitle = ref('')
const previewVisible = ref(false)

function getBase64(img: any, callback: (base64Url: string) => void) {
  const reader = new FileReader()
  reader.addEventListener('load', () => callback(reader.result as string))
  reader.readAsDataURL(img)
}
watch(
    () => props.value,
    (newValue) => {
      console.log('tempObj')
      if (newValue) fileList.value = newValue
    }
);


async function handlePreview(file: any) {
  if (file.url) {
    previewImage.value = file.url
    previewVisible.value = true
  } else {
    previewTitle.value =
      file.name || file.url.substring(file.url.lastIndexOf('/') + 1)
    getBase64(file.originFileObj, (base64Url: string) => {
      previewImage.value = base64Url
      previewVisible.value = true
    })
  }
}

function handleCancel() {
  previewVisible.value = false
  previewTitle.value = ''
}
const handleChange = (info: UploadChangeParam) => {
  console.log('info', info)
  emit('update:value', fileList.value)
}

async function handleUpload(fn: (fileList: any) => Promise<void>) {
  loading.value = true
  try {
    await fn(fileList.value)
    loading.value = false
  } catch (e) {
    loading.value = false
    console.log('e', e)
  }
}

const beforeUpload = (file: any, files: any) => {
  return new Promise((resolve, reject) => {
    const allowedTypes = props.type.split(',') // 将 type 属性的值拆分为一个文件类型的数组
    const fileType = file.type.split('/')[1] // 获取文件的后缀类型
    const isAllowedType = allowedTypes.includes(fileType)

    const isLtMaxSize = file.size / 1024 / 1024 < maxSize
    if (!isAllowedType) {
      message.error(`请选择${props.type}类型文件!`)
      return false
    } else if (!isLtMaxSize) {
      message.error(`图片不能超过 ${maxSize}MB!`)
      return false
    } else {
      return reject(false)
    }
  })
}
defineExpose({ handleUpload })
</script>
<style scoped>
:deep .ant-upload-wrapper.ant-upload-picture-card-wrapper {
  width: auto;
}
.upload-tips {
  display: flex;
  flex-direction: column;
  justify-content: center;
  font-size: 13px;
  font-weight: 400;
  color: rgba(49, 73, 103, 0.5);
  .striking {
    color: #1bc47d;
  }
}
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>
